604C - Alternative Thinking - CodeForces Solution


constructive algorithms dp greedy math *1600

Please click on ads to support us..

Python Code:

n = int(input())
s = input()

l = []
cnt, ans = 0, 0
last = ''
for i in s:
    if i != last:
        l.append(cnt)
        cnt = 1
    else:
        cnt += 1
    last = i
l.append(cnt)
l = l[1:]
a, b = 0, 0
for t in l:
    if t > 1:
        a += 1
    if t > 2:
        b += 1
if a >= 2 or b >= 1:
    print(len(l)+2)
    exit()
if a == 1:
    print(len(l)+1)
    exit()
print(len(l))

C++ Code:

#define _CRT_SECURE_NO_WARNINGS
#include<set>
#include<iostream>
#include<vector>
#include<math.h>
#include<string>
#include<sstream>
#include<string>
#include<map>
#include<unordered_map>
#include<queue>
#include<unordered_set>
#include <cstring>
#include <algorithm>
#include <bitset>

using namespace std;
#define all(x) x.begin(), x.end()
#define endl '\n'
#define sz(x) x.size()
#define clr(x,v)  memset(x,v,sizeof x);
typedef  long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

void fast()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);

#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
#endif

}

const int N = 1e5 + 5, MOD = 1e9 + 7;
char s[N];
int n;
int dp[N][2][3];
int solve(int i, int last, int state) {
	if (i == n)return 0;

	int& ret = dp[i][last][state];
	if (~ret)return ret;
	ret = 0;

	int cur = s[i] - '0';
	if (state == 1)cur = !cur;
	ret = (last!=cur) + solve(i + 1, cur, state);

	if (state == 0&& last == cur) 
			ret = max(ret,1+ solve(i + 1, !cur, 1));
	
	else if (state == 1&&last==cur)
			ret = max(ret, 1 + solve(i + 1, !cur, 2));
		
	
	else if(state==2){
		if (last != s[i] - '0')
			ret = 1 + solve(i + 1, s[i] - '0', 2);
		else
			ret = solve(i + 1, s[i] - '0', 2);
	}
	return ret;

}
int main()

{
	fast();
	cin >> n >> s;
	clr(dp, -1);
	cout << solve(0, 1 - (s[0] - '0'), 0);
}

 		 			 			   	  	  			 	 	  	


Comments

Submit
0 Comments
More Questions

97. Interleaving String
543. Diameter of Binary Tree
124. Binary Tree Maximum Path Sum
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
501A - Contest
160A- Twins
752. Open the Lock
1535A - Fair Playoff
1538F - Interesting Function
1920. Build Array from Permutation
494. Target Sum
797. All Paths From Source to Target
1547B - Alphabetical Strings
1550A - Find The Array
118B - Present from Lena
27A - Next Test
785. Is Graph Bipartite
90. Subsets II
1560A - Dislike of Threes
36. Valid Sudoku
557. Reverse Words in a String III
566. Reshape the Matrix
167. Two Sum II - Input array is sorted
387. First Unique Character in a String
383. Ransom Note
242. Valid Anagram
141. Linked List Cycle
21. Merge Two Sorted Lists
203. Remove Linked List Elements
733. Flood Fill